package cn.declare.controller;


import cn.declare.bean.User;
import cn.declare.service.impl.UserServiceImpl;

import cn.declare.utils.JWTUtil;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.SignatureException;
import org.apache.ibatis.ognl.TokenMgrError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.transform.Result;
import java.util.HashMap;
import java.util.Map;

/**
 * Author 葛鑫
 * 用户登录
 */
@RestController
public class UserController {
    @Resource
    private UserServiceImpl service;

    /**
     * Author：葛鑫
     * 登录创建token
     * @param user
     * @return
     */
    @PostMapping("/user/login")
    public Map <String,Object> doLogin(@RequestBody User user){
        Map<String,Object> map= new HashMap<>();
        User userDB = service.login(user.getUserCode(), user.getUserPassword());
        try{
            if (userDB.getId()!=0){
                Map<String,Object> payload=new HashMap<>();
                payload.put("id",userDB.getId());
                payload.put("name",userDB.getUserName());
                payload.put("roleId",userDB.getRoleId());
                payload.put("tradeId",userDB.getTradeId());
                payload.put("userType",userDB.getUserType());
                payload.put("userCode",userDB.getUserCode());
                String token = JWTUtil.createToken(payload);
                map.put("state",true);
                map.put("msg","认证成功！");
                map.put("token",token);

                map.put("roleId",userDB.getRoleId());
                map.put("tradeId",userDB.getTradeId());
                map.put("userId",userDB.getId());

            }
        }catch (Exception e){
            map.put("state",false);
            map.put("msg","认证失败");
        }
        return map;
    }

    /**
     * Author：葛鑫
     * 解析 token 获取用户数据
     * @param request
     * @return
     */
    @GetMapping("/user/dologin")
    public Map<String,Object> login(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader("token");
//        在控制台打印token
        System.out.println("------------------");
        System.out.println(token);
        Jwt jwt = JWTUtil.checkToken(token);
        map.put("user",jwt.getBody());
        map.put("state", true);
        map.put("msg", "请求成功！");
        return map;
    }
}
